package com.example.servlet;

import com.example.model.Book;
import com.example.util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.*;

@WebServlet(name = "BookServlet", urlPatterns = "/books")
public class BookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession(false);
        Integer userId = session != null ? (Integer) session.getAttribute("user_id") : null;
        List<String> wrongTypes = new ArrayList<>();
        if (userId != null) {
            // 查询用户错题类型统计
            try (Connection conn = DBUtil.getConnection();
                 PreparedStatement ps = conn.prepareStatement(
                         "SELECT qq.type, COUNT(*) as cnt FROM wrong_questions wq JOIN quiz_questions qq ON wq.question_id=qq.id WHERE wq.user_id=? GROUP BY qq.type ORDER BY cnt DESC")
            ) {
                ps.setInt(1, userId);
                try (ResultSet rs = ps.executeQuery()) {
                    while (rs.next()) {
                        wrongTypes.add(rs.getString("type"));
                    }
                }
            } catch (Exception e) {
                System.out.println("错题统计查询失败: " + e.getMessage());
            }
        }
        // 查询所有图书
        List<Book> allBooks = new ArrayList<>();
        String dbError = null;
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM books")) {
            while (rs.next()) {
                Book book = new Book();
                book.setId(rs.getInt("id"));
                book.setName(rs.getString("name"));
                book.setAuthor(rs.getString("author"));
                book.setPrice(rs.getBigDecimal("price"));
                book.setStock(rs.getInt("stock"));
                book.setDescription(rs.getString("description"));
                book.setCoverUrl(rs.getString("cover_url"));
                allBooks.add(book);
            }
        } catch (Exception e) {
            dbError = "数据库连接失败：" + e.getMessage();
            e.printStackTrace();
        }
        // 按错题类型优先排序
        allBooks.sort((b1, b2) -> {
            int idx1 = wrongTypes.indexOf(b1.getType());
            int idx2 = wrongTypes.indexOf(b2.getType());
            if (idx1 == -1 && idx2 == -1) return b2.getClicks() - b1.getClicks(); // 都不在错题类型，按点击量
            if (idx1 == -1) return 1;
            if (idx2 == -1) return -1;
            return idx1 - idx2;
        });
        req.setAttribute("books", allBooks);
        req.setAttribute("dbError", dbError);
        req.getRequestDispatcher("books.jsp").forward(req, resp);
    }
} 